package kr.couponplay.android.activity.search;

import java.util.ArrayList;

import kr.couponplay.android.activity.R;
import kr.couponplay.android.activity.TitleBarHelper;
import kr.couponplay.android.activity.TitleBarHelper.TabMenuType;
import kr.couponplay.android.activity.TitleBarHelper.TitleLayout;
import kr.couponplay.android.domain.BeanFactory;
import kr.couponplay.android.domain.deal.Deal;
import kr.couponplay.android.domain.deal.DealDao;
import kr.couponplay.android.domain.deal.DealList;
import kr.couponplay.android.support.AlertUtils;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak") 
public class SearchActivity extends FragmentActivity {
	private static final TabMenuType TAB_MENU_TYPE = TabMenuType.SEARCH;
	private SearchActivity activity = this;
	public EditText searchInput;
	private Button btnSearch;
	private SearchButtonOnClickListener searchButtonListener;
	private SearchSubMenuButtonOnClickListener searchSubMenuButtonOnClickListener;
	
	public ViewPager searchListViewPager;
	private SearchFragmentPagerAdapter searchListViewPagerAdapter;
	private ProgressDialog dataLoadingDialog;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.search_activity);
        
        drawTop();
        drawSubMenu();
        drawBody();
    }
	
	@Override
	public void onResume() {
		super.onResume();
		TitleBarHelper.setVisibable(TAB_MENU_TYPE);
	}
	
	private void drawTop() {
		LinearLayout titleLinearLayout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.search_title, null);
		TitleBarHelper.addTitleLayout(new TitleLayout(titleLinearLayout, TAB_MENU_TYPE));
		
		searchButtonListener = new SearchButtonOnClickListener(activity);
		
        searchInput = (EditText)titleLinearLayout.findViewById(R.id.search_input);
        searchInput.setOnEditorActionListener(searchButtonListener);
        searchInput.setOnFocusChangeListener(searchButtonListener);
        
        ImageView deleteView = (ImageView)titleLinearLayout.findViewById(R.id.search_input_delete);
        deleteView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchInput.setText("");
			}
        });
        
        btnSearch = (Button)titleLinearLayout.findViewById(R.id.goSearch);
        btnSearch.setOnClickListener(searchButtonListener);
	}
	
	private void drawSubMenu() {
		searchSubMenuButtonOnClickListener = new SearchSubMenuButtonOnClickListener(activity);
		
		Button recentQuery = (Button)findViewById(R.id.recent_query);
		recentQuery.setOnClickListener(searchSubMenuButtonOnClickListener);
		SearchSubMenuHelper.add(recentQuery);

		Button searchResult = (Button)findViewById(R.id.search_result);
        searchResult.setOnClickListener(searchSubMenuButtonOnClickListener);
        SearchSubMenuHelper.add(searchResult);
        
        SearchSubMenuHelper.drawSelectButton(recentQuery);
	}
	
	private void drawBody() {
		searchListViewPager =(ViewPager)findViewById(R.id.search_viewpager);
		searchListViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			@Override
			public void onPageSelected(int position) {
				SearchSubMenuHelper.drawSelectButton(SearchSubMenuHelper.get(position));
			}
        });
		searchListViewPagerAdapter = new SearchFragmentPagerAdapter(activity, new DealList(null, new ArrayList<Deal>()));
        searchListViewPager.setAdapter(searchListViewPagerAdapter);
        searchListViewPager.setCurrentItem(0);
    };
    
	public void goSearch() {
		final String query = searchInput.getText().toString();
		if (query == null || query.trim().length() == 0) {
    		LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.toast_layout, null);
    		TextView textView = (TextView)layout.findViewById(R.id.toast_text);
    		textView.setText("검색어를 입력해 주세요.");
    		Toast toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    		toast.setView(layout);
    		toast.show();
			btnSearch.setFocusable(true);
			return;
		}
		
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);
		
		dataLoadingDialog = ProgressDialog.show(activity, null, "데이터 수신중입니다.", true, false);
		Thread thread = new Thread(new Runnable() {
			public void run() {
				Message msg = Message.obtain();
				try {
					msg.obj = BeanFactory.getBean(activity.getApplicationContext(), DealDao.class).search(query, 0);
				} catch (Exception e) {
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		});
		thread.start();
	}
	
	private Handler handler = new Handler() {
	    public void handleMessage(Message msg) {
	    	if (msg.obj instanceof Throwable) {
	    		alert((Exception)msg.obj);
	    		dataLoadingDialog.dismiss();
	    		return;
	    	}
	    	DealList dealList = (DealList)msg.obj;
	    	searchListViewPagerAdapter = new SearchFragmentPagerAdapter(activity, dealList);
	    	searchListViewPager.removeAllViewsInLayout();
	    	searchListViewPager.removeAllViews();
	    	searchListViewPagerAdapter.replace();
	    	searchListViewPager.setAdapter(searchListViewPagerAdapter);
	    	searchListViewPager.setCurrentItem(1);
		    dataLoadingDialog.dismiss();
	    }
	};
	
    public void alert(Exception exception) {
        AlertUtils.errorAlert(this, exception);
    }	
	
    @Override
    public void onBackPressed() {
    	TitleBarHelper.getTabHost().setCurrentTab(0);
    }
}
